package net.yebaihe.xqbz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.meizu.mstore.license.ILicensingService;
import com.meizu.mstore.license.LicenseCheckHelper;
import com.meizu.mstore.license.LicenseResult;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class BizhixinqingActivity extends Activity {
    private static final String PREFS_NAME = "xqbz";
	/** Called when the activity is first created. */
	
	Object[][]questions={
			{"你迷失在灯红酒绿中吗？",R.drawable.c01,"也许有时候，你需要一个人静下心来想一想……"},
			{"时常会觉得孤单吗？",R.drawable.c02,"不要害怕孤单，其实人最好的朋友，是自己的心灵。"},
			{"冬天要来了，觉得冷吗？",R.drawable.c03,"我愿温暖你，愿你在夜里有一个温暖的好梦。"},
			{"经常沉浸在对过往的回忆里吗？",R.drawable.c04,"我希望你能带着温暖的回忆，寻找更温暖的未来！"},
			{"今天的心情好吗？",R.drawable.c05,"保持好心情，我喜欢你的微笑！"},
			{"总是在等待？什么人，什么事，或是未知的机会？",R.drawable.c06,"等待让人不安，却给人无限希望，我会陪你等待。"},
			{"时常觉得生活很枯燥吗？",R.drawable.c07,"给自己一个大胆颜色，做一些大胆的事情吧！"},
			{"有那么一个人能温暖你的心吗？",R.drawable.c08,"幸福就是和最爱的人相互温暖！"},
			{"还在坚持自己的梦想吗？",R.drawable.c09,"就算你的梦想已经斑驳，它永远都是你心里最美好的向往。"},
			{"那个你讨厌的人，又让你不顺心了吧？",R.drawable.c10,"让那些烦恼都去见鬼，干净的世界里，你才是主角。"},
			{"冷漠、孤单、沮丧……这些词常常会出现吗？",R.drawable.c11,"我想对你说：迎着太阳，影子就会被你甩在身后。"},
			{"想自己一个人躲起来偷偷哭吗？",R.drawable.c12,"看到了吗？在五颜六色的青春里，泪水也是彩色的！"},
			{"左还是右呢？你经常不知道该如何选择？",R.drawable.c13,"其实你明白，只有一个方向，它最接近你的内心！"},
			{"生活让你感到绝望吗？",R.drawable.c14,"几米说：我总是在最深的绝望里，看见最美的风景，把这句话送给你。"},
			{"觉得爱情是一种折磨吧？",R.drawable.c15,"就算是折磨，也让人无可自拔，这就是爱情。"},
			{"爱情给你带来了无比的幸福感，是吗？",R.drawable.c16,"谢谢你的爱，让我拥有了整个星空。"},
			{"自己一路走来，很不容易吧？",R.drawable.c17,"抱抱自己，告诉自己内心强大的人都是孤独的。"},
			{"不知该如何对TA表达你的爱吗？",R.drawable.c18,"一句我爱你，一个小惊喜，给爱加点特别的味道！"},
			{"觉得自己的梦想很难实现吗？",R.drawable.c19,"我想对你说：就算梦想再遥不可及，也要尽量让它飞得远些！"},
			{"是否觉得烦燥、无法静下心来？",R.drawable.c20,"送给你一幅画，还有这几个字：心素如简，人淡如菊"},
			{"你会问：为什么这个世界和我想像的不一样吗？",R.drawable.c21,"是的，幻想往往是由多色绘成，现实却以黑白色呈现。"},
			{"有时会感觉自卑吗？",R.drawable.c22,"每个人的身上都有属于自身独特的光芒，那是别人无法模仿和拥有的，我喜欢你！"},
			{"一直在渴望自由却总是认为得不到吗？",R.drawable.c23,"如果不能打破心的禁锢，即使给你整个天空，你也找不到自由的感觉。"},
			{"会感觉压力超过了自己能承受的范围吗？",R.drawable.c24,"其实生活的一大乐趣，便是完成别人认为你不能做到的事情，加油！"},
			{"一直在寻寻觅觅却一直遇不到你的TA吗？",R.drawable.c25,"有一天，会有一个人走进你的生活，并且让你明白为什么你和其他人都没有结果。"},
			{"时常会用“一团麻”来形容自己的生活吗？",R.drawable.c26,"试着让生活变得简单，对幸福或寂寞顺其自然。"},
			{"会刻意逃避困难，认为自己根本解决不了？",R.drawable.c27,"只有在勇敢面对困境的时候，你才知道自己像树一样独立而坚强。"},
			{"总是觉得为了别人而活着吗?",R.drawable.c28,"跟自己说声对不起，因为你为了别人难为了自己。"},
			{"你一直在介意别人对你的看法吗？",R.drawable.c29,"何必向不值得的人证明什么，生活得更好，是为你自己。"},
			{"在逐梦的道路上总是觉得无助、孤单？",R.drawable.c30,"如果你无法忍受孤独，就不要追逐梦想，每一个成功的人，都有一段沉默的时光。"},
			{"有些悲哀到现在都无法释怀吗？",R.drawable.c31,"人最悲哀的，并不是昨天发生过的，而是沉浸于昨天的悲哀之中。努力走出来吧！"},
			{"周围总会有那么一些人，在等着看你的笑话？",R.drawable.c32,"人生就像愤怒的小鸟，每次你失败的时候，总有几只猪在笑。你要做的就是无视嘲笑，自信地微笑！"},
			{"总是告诫自己要知足常乐？",R.drawable.c33,"有欲望并不可耻，叔本华说：生命是一团欲望，欲望不满足便空虚，满足便无聊。"},
			{"身边总有那么一些人对你指指点点、说三道四？",R.drawable.c34,"你做的越对，背后说你的人越多；你过的越好，背后讥讽你的人越多。看清这点，继续你的绚烂吧！"},
			{"总觉得自己得到的爱不够多？",R.drawable.c35,"与其等着别人来爱你，不如学着努力多爱自己一点！"},
			{"总是羡慕别人的生活，幻想自己是某个故事的主人公吗？",R.drawable.c36,"请你相信，在别人眼中，你也是一道美丽的风景！"},
			{"被误解的时候，你会大声为自己辩解吗？",R.drawable.c37,"不是所有的人都了解你，不必对全世界喊话。在多说无益的时候，沉默才是最好的解释。"},
			{"很多人都戴着面具，你总试图去看清真面目？",R.drawable.c38,"时间会证明一切，到最后，你总会明白，谁是虚情假意，谁是真心实意，谁为了你不顾一切。"},
			
			
	};
	String[] byebye={
			"see you next time",
			"bye",
			"下次见！",
	};
	ArrayList<Integer> qasked=new ArrayList<Integer>();
	ArrayList<String> localquestions=new ArrayList<String>();
	private TextView y;
	private TextView n,na;
	ArrayList<String> thumbNeedCreate=new ArrayList<String>();
	
	protected CharSequence[] _options = { "设为桌面壁纸", "设为待机壁纸","虚拟人物可见","仅显示自定义壁纸"};
	protected boolean[] _selections =  {true,true,true,false};
	
	private ILicensingService mLicensingService = null;
	private ServiceConnection mLicenseConnection =new ServiceConnection() {
		public void onServiceDisconnected(ComponentName name) {
			mLicensingService = null;
		}
		public void onServiceConnected(ComponentName name, IBinder service){
			mLicensingService = ILicensingService.Stub.asInterface(service);
			try {
				valid=false;
				checkValid();
			} catch (RemoteException e) {
				tipString = "软件未授权，无法继续使用，请到魅族软件中心下载并付费，谢谢支持！";
				valid=false;
			}
			if (!valid){
				Toast.makeText(BizhixinqingActivity.this, tipString, Toast.LENGTH_LONG).show();
				finish();
			}
		}
	};
	private boolean valid=false;//是否缴费
	private String tipString="";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		y=(TextView) this.findViewById(R.id.idyes);
		y.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				changeWallPaper((Integer)v.getTag());
			}
		});
		
		n=(TextView) this.findViewById(R.id.idno);
		n.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				nextQuestion();
			}
		});
		
		na=(TextView) this.findViewById(R.id.iddont);
		na.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				notaskagain((Integer)v.getTag());
				nextQuestion();
			}
		});
		
		checkConfig();
		loadLocalQuestion();
		nextQuestion();

		//checkPayed();
    }

    private void loadLocalQuestion() {
    	//check if index file there,if not,make it from asserts directory
    	File f=new File(getBaseDir()+"index.txt");
    	if (!f.exists()){
    		saveAssertsToBase("index.txt");
    		saveAssertsToBase("a.jpg");
    		saveAssertsToBase("b.jpg");
    	}
    	
    	localquestions.clear();
    	//read index files
    	File file = new File(getBaseDir()+"index.txt");
    	try {
    	    BufferedReader br = new BufferedReader(new FileReader(file));
    	    String line;
    	    while ((line = br.readLine()) != null) {
    	    	String[] ps=line.split(" ",2);
    	    	File ft=new File(getBaseDir()+ps[0]);
    	    	if (ft.exists()){
    	    		localquestions.add(line);
    	    	}
    	    }
    	}
    	catch (IOException e) {
    	}
    	
	}

	private void saveAssertsToBase(String string) {
		AssetManager am = getAssets();
		InputStream is;
		try {
			is = am.open(string);
			String path=getBaseDir()+string;
			File fd=new File(path);
			if (!fd.exists()){
				FileOutputStream os = new FileOutputStream(path);
				byte[] buf = new byte[1024];
				int n = 0;
				int o = 0;
				while ((n = is.read(buf, o, buf.length)) != -1) {
					os.write(buf, 0, n);
				}
				is.close();
				os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getBaseDir() {
		String basedir=Environment.getExternalStorageDirectory()+"/xqbz/";
		File f=new File(basedir);
		if (!f.exists()) f.mkdirs();
		return basedir;
	}

	protected void notaskagain(int idx) {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  
		SharedPreferences.Editor editor = settings.edit(); 
		if (idx<questions.length){
			editor.putBoolean("show"+idx, false);
		}
		else{
			String[] ps=localquestions.get(idx-questions.length).split(" ",2);
			editor.putBoolean("show"+ps[0], false);
		}
		editor.commit(); 
	}

	private void checkConfig() {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  
        _selections[0] = settings.getBoolean("desktop",true);
        _selections[1] = settings.getBoolean("lock",true);
        _selections[2] = settings.getBoolean("char",true);
        _selections[3] = settings.getBoolean("localonly",false);
        
		View v=findViewById(R.id.idgirl);
		if (_selections[2]){
			v.setVisibility(View.VISIBLE);
		}
		else{
			v.setVisibility(View.GONE);
		}
	}

	protected void checkValid() throws RemoteException {
		final String APKPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHLKYA9gmr/anmrn4bhdJjfFb2wqU/onzpUb3p/qUwyHNt+PczNB2KZCBkXKTtToyq+hBfEhIFjOXg5mrU2Xs/Ajj4kPBeInEXRKSBYNzuLdmWCunZWM1qiDs0LrGNrWsuc/s4Rpvd1SkySwgIneFc4Ss25YKqY+g2Fi2NM6R+twIDAQAB";
		LicenseResult result = mLicensingService.checkLicense(getApplication().getPackageName());
		if(result.getResponseCode() == LicenseResult.RESPONSE_CODE_SUCCESS){
			boolean bSuccess = LicenseCheckHelper.checkResult(APKPublicKey, result);
			if(bSuccess &&
					result.getPurchaseType() == LicenseResult.PURCHASE_TYPE_NORMAL){
				valid=true;
			} 
			else 
			{
    			if(bSuccess &&
    			result.getPurchaseType() == LicenseResult.PURCHASE_TYPE_TRIAL){
    				Calendar cal = result.getStartDate();
    				Calendar now = Calendar.getInstance();
    				tipString = "您的\"试用版本\"已经过期，请到魅族软件中心付费后继续使用，谢谢支持!";
    				final int expireDays = 1;
    				now.add(Calendar.DAY_OF_MONTH, -expireDays);
    				int yearNow = now.get(Calendar.YEAR);
    				int monthNow = now.get(Calendar.MONTH) + 1;  //< +1是因为Calendar默认的月份是从0开始的
    				int dayNow = now.get(Calendar.DAY_OF_MONTH);
    				
    				int year = cal.get(Calendar.YEAR);
    				// ！！！注意，这里获取到的月份（MONTH）是从"1",开始而非Calendar api中的"0"值！！！
    				int month = cal.get(Calendar.MONTH);
    				int day = cal.get(Calendar.DAY_OF_MONTH);

    				if(year > yearNow ||
    						(year == yearNow && month > monthNow) ||
    						(year == yearNow && month == monthNow && day >= dayNow)){
    					Toast.makeText(this, "您正在使用的是体验版，感谢您的支持!", Toast.LENGTH_LONG).show();
    					valid=true;
    				}else{
    					valid=false;
    				}
    			}else{
    				tipString = "软件未授权，无法继续使用，请到魅族软件中心下载并付费，谢谢支持！";
    				valid=false;
    			}
			}
		} else {
			tipString = "软件未授权，无法继续使用，请到魅族软件中心下载并付费，谢谢支持！";
			valid=false;
		}
    	// 在使用完成后，必须解除绑定
    	if(mLicensingService!= null){
    		unbindService(mLicenseConnection);
    	}
	}

	private void checkPayed() {
    	if(mLicensingService == null){
    		Intent intent = new Intent();
    		intent.setAction(ILicensingService.class.getName());
    		bindService(intent, mLicenseConnection, Context.BIND_AUTO_CREATE);
    	}
    }

	protected void nextQuestion() {
		

		/*if (qasked.size()>2){
			randomWallPaper();
			return;
		}*/
		
		int idx=randomQuestion();
		if (idx<0) return;
		askQuestion(idx);
		qasked.add(idx);
	}

	private int randomQuestion() {
		int [] aques=new int[questions.length+localquestions.size()];
		int total=0;
		int notshowtotal=0;
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
        if (!_selections[3]){
        	for (int i=0;i<questions.length;i++){
        		if (qasked.indexOf(i)<0){
        			if (settings.getBoolean("show"+i,true)){
        				aques[total]=i;
        				total+=1;
        			}
        			else{
        				notshowtotal+=1;
        			}
        		}
        	}
        }
		for (int i=0;i<localquestions.size();i++){
			String[]ps=localquestions.get(i).split(" ",2);
			if (qasked.indexOf(questions.length+i)<0){
				//if (settings.getBoolean("show"+ps[0], true)){
				aques[total]=questions.length+i;
				total+=1;
				//}
			}
		}

		if (total<=0){
			if (qasked.size()<=0){
				Toast.makeText(this, "也许应该增加一些场景了！", Toast.LENGTH_LONG).show();
				return 0;
			}
			else{
				qasked.clear();
				return randomQuestion();
			}
		}

		int idx=(int) (new Date().getTime() % total);
		return aques[idx];
	}

	private void askQuestion(int idx) {
		final TextView t=(TextView) this.findViewById(R.id.idquestion);
		String q="";
		if (idx<questions.length) {
			q= questions[idx][0].toString();
		}
		else{
			String[] ps=localquestions.get(idx-questions.length).split(" ");
			if (ps.length>=2){
				q=ps[1].trim();
			}
		}
		final String question=q;
		Animation am1 = new AlphaAnimation ( 1, 0 );
		am1. setDuration ( 1000 );
		Animation am2=new TranslateAnimation(0, 0, 0, -10);
		am2. setDuration ( 1000 );
		AnimationSet am = new AnimationSet ( false );
		am.addAnimation(am1);
		am.addAnimation(am2);
		am.setAnimationListener(new AnimationListener(){
			public void onAnimationEnd(Animation animation) {
				t.setText(question);
			}

			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationStart(Animation animation) {
			}
			
		});
        if (t.getText().toString().trim().length()>0){
        	t.startAnimation(am);
        }
        else{
			t.setText(question);
        }
		y.setTag(idx);
		na.setTag(idx);
		if (idx<questions.length){
			na.setVisibility(View.VISIBLE);
			y.setText("是的");
			n.setText("不是");
		}
		else{
			y.setText("这一个");
			n.setText("下一个");
			na.setVisibility(View.GONE);
		}
	}

	protected void changeWallPaper(int idx) {
		final int curidx=idx;
		final View l=this.findViewById(R.id.idmask);
		Animation anim = null;  
        anim = new AlphaAnimation(1.0f,0.0f);  
        anim.setInterpolator(new AccelerateDecelerateInterpolator());  
        anim.setDuration(2000);  
		l.setVisibility(View.VISIBLE);
        anim.setAnimationListener(new AnimationListener(){
			public void onAnimationEnd(Animation animation) {
				l.setVisibility(View.GONE);
				new Handler().postDelayed(new Runnable(){
					public void run() {
						Toast.makeText(BizhixinqingActivity.this, getByeWords(), Toast.LENGTH_LONG).show();
						finish();
					}

					private CharSequence getByeWords() {
						int idx=(int) (new Date().getTime() % byebye.length);
						return byebye[idx];
					}
				},4000);
			}
			public void onAnimationRepeat(Animation animation) {
			}

			public void onAnimationStart(Animation animation) {
				WallpaperManager manager = WallpaperManager.getInstance(BizhixinqingActivity.this);
				try {
					if (curidx<questions.length){
						int resid=(Integer) questions[curidx][1];
						if (_selections[0]) manager.setResource(resid);
						if (_selections[1]) manager.setResourceToLockWallpaper(resid);
					}
					else{
						String[] ps=localquestions.get(curidx-questions.length).split(" ",2);
						FileInputStream s=new FileInputStream(getBaseDir()+ps[0]);
						//Bitmap b=BitmapFactory.decodeFile();
						if (_selections[0]) manager.setStream(s);
						s.close();
						s=new FileInputStream(getBaseDir()+ps[0]);
						if (_selections[1]) manager.setStreamToLockWallpaper(s);
						s.close();
					}
				} catch (IOException e) {
					Toast.makeText(BizhixinqingActivity.this, "设置壁纸失败，Sorry!", Toast.LENGTH_LONG).show();
					return;
				}
				TextView t=(TextView) findViewById(R.id.idquestion);
				if (curidx<questions.length){
					t.setText(questions[curidx][2].toString());
				}
				y.setVisibility(View.INVISIBLE);
				n.setVisibility(View.INVISIBLE);
				na.setVisibility(View.INVISIBLE);
				View v=findViewById(R.id.idgirl);
				v.setVisibility(View.INVISIBLE);
			}
        });
        l.startAnimation(anim); 
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
    	menu.add(Menu.NONE, Menu.FIRST + 1, 3, "设置").setIcon(R.drawable.set01);
    	menu.add(Menu.NONE, Menu.FIRST + 2, 3, "还原").setIcon(R.drawable.set02);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			showConfigDialog();
		break;
		case Menu.FIRST + 2:
			allowaskall();
		break;
		}
		return true;
	}

	private void allowaskall() {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  
		SharedPreferences.Editor editor = settings.edit();  
		for (int i=0;i<questions.length;i++){
			editor.putBoolean("show"+i, true);  
		}
		editor.commit(); 
		Toast.makeText(this, "所有问题已复位到初始状态", Toast.LENGTH_SHORT).show();
	}

	private void showConfigDialog() {
		new AlertDialog.Builder( this )
	       .setTitle(R.string.app_name)
	       .setMultiChoiceItems( _options, _selections, new DialogInterface.OnMultiChoiceClickListener() {
			
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				_selections[which]=isChecked;
			}
		})
	       .setPositiveButton( "确定", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
		        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  
				SharedPreferences.Editor editor = settings.edit();  
				editor.putBoolean("desktop", _selections[0]);  
				editor.putBoolean("lock", _selections[1]);  
				editor.putBoolean("char", _selections[2]);  
				editor.putBoolean("localonly", _selections[3]);  
				editor.commit(); 
				View v=findViewById(R.id.idgirl);
				if (_selections[2]){
					v.setVisibility(View.VISIBLE);
				}
				else{
					v.setVisibility(View.GONE);
				}
			}
		})
	       .create().show();
	}
}